<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Weixinapi extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->library('weixin');
	}

	public function index()
	{	
		// 没接收到用户发送过来的信息？	
		if ( ! $msg = $this->weixin->msg())
		{
			// todo

			return;
		}

		// 用户发送的是地理位置?
		if ((string)$msg->MsgType == 'location')
		{	
			// todo

			return;
		}		
		// 用户关注微信账号后的自动回复 unsubscribe
		if ((string)$msg->Event == 'subscribe')
		{
			$this->weixin->send('text', array(
			'to'      => (string)$msg->FromUserName,
			'from'    => (string)$msg->ToUserName,
			'time'    => time(),
			'content' => "非常感谢关注爱厨房（www.ichufang.cn）,您可以直接用语音或者文字告诉我 食材 或 菜名 我可以帮您想想怎么做~"
			));		

			return;		
		}

		// 用户发送文本信息？
		if ((string)$msg->MsgType == 'text' || (string)$msg->MsgType == 'voice')
		{
			$content_date = $msg->Content ? $msg->Content : $msg->Recognition;

			if ($content_date)
			{
				$caipunews = $this->_weixinnews((string)$content_date);
				// 发送图文回复
				if($caipunews)
				{
					$this->weixin->send('news', array(
						'to'      => (string)$msg->FromUserName,
						'from'    => (string)$msg->ToUserName,
						'time'    => time(),
						'items'   => $caipunews
					));
					return;		
				}
				else
				{
					$this->weixin->send('text', array(
						'to'      => (string)$msg->FromUserName,
						'from'    => (string)$msg->ToUserName,
						'time'    => time(),
						'content' => '食材搜索：“牛肉” “番茄 鸡蛋” ；菜谱搜索：“番茄炒鸡蛋”，“土豆炖牛肉” '
					));
					return;	
				}
						
			}
		}
	}
	public function create_menu()
	{
		$this->weixin->create_menu();
	}
	public function _weixinnews($content = '')
	{
		$mobile_url = 'http://m.ichufang.cn/recipe/';
		$news = array();
		$news_array = array();
		$this->load->model('Caipu_mdl');
		$query = $this->Caipu_mdl->get_caipu_weixin($content, 0, 10)->result_array();
		foreach ($query as $value) {
			$news['title'] = $value['title'];
			$news['description'] = '';
			$news['picurl'] = server_img($value['coverImage']);
			$news['url'] = $mobile_url.$value['id'];
			$news_array[] = $news;
		}
		return $news_array;
	}
}

